package com.boruan.qq.zxgylibrary.ui.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/8/6.
 * des: 药品分类页面
 */

public class DrugClassifyActivity extends BaseActivity {

    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;
    @BindView(R2.id.drug_classify_name)
    TextView drugClassifyName;
    @BindView(R2.id.web_view)
    WebView classifyWeb;

    private CustomDialog customDialog;

    private String mDrugName;
    private int cId;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_drug_classify;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        if (getIntent() != null){
            mDrugName = getIntent().getStringExtra("drugName");
            cId = getIntent().getIntExtra("cId",0);
            drugClassifyName.setText(mDrugName);
        }
        customDialog = new CustomDialog(this, R.style.CustomDialog);
		if (classifyWeb == null){
            Toast.makeText(this, "该页面有些异常，请稍后重试！", Toast.LENGTH_SHORT).show();
            finish();
        }else {
            customDialog.show();
			initWeb(ConstantInfo.baseUrl + "drugList?type=android&cid=" + cId + "&token=" + ConstantInfo.h5UserToken);//webView写在布局里
        }
        
    }

    @JavascriptInterface
    public void clickEnterPharmacy(String id,String shopCid,String skuId){//点击进入药店详情
        Log.i("id",id + "lala");
        Intent intent = new Intent(DrugClassifyActivity.this, PharmacyHomePageActivity.class);
        intent.putExtra("shopCid",shopCid);
        intent.putExtra("skuid",skuId);
        intent.putExtra("id",id);
        startActivity(intent);
    }


    /**
     * 初始化web
     */
    private void initWeb(final String richText) {

        //初始化webView
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                classifyWeb.getSettings().setJavaScriptEnabled(true);
                classifyWeb.getSettings().setSupportZoom(true);
                classifyWeb.getSettings().setBuiltInZoomControls(true);
                classifyWeb.getSettings().setDisplayZoomControls(false);
                classifyWeb.setVerticalScrollBarEnabled(false);

                classifyWeb.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                classifyWeb.getSettings().setLoadWithOverviewMode(true);
                classifyWeb.getSettings().setUseWideViewPort(true);
                classifyWeb.getSettings().setTextZoom(100);
                classifyWeb.getSettings().setDomStorageEnabled(true);

                classifyWeb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//默认先不使用缓存
                classifyWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
                classifyWeb.getSettings().setDefaultTextEncodingName("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    classifyWeb.getSettings().setMixedContentMode(classifyWeb.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
                }
                classifyWeb.loadUrl(richText);
                classifyWeb.addJavascriptInterface(DrugClassifyActivity.this, "control");
                //classifyWeb.setWebViewClient(new HtmlUtils.MyWebViewClient());
                classifyWeb.setWebViewClient(new WebViewClient() {
                    @Override
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);

                    }

                    @Override
                    public void onPageFinished(WebView view, String url) {
                        super.onPageFinished(view, url);
                        customDialog.dismiss();
                    }

                    @Override
                    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                        handler.proceed();//接受所有网站的证书，忽略SSL错误
                        
                    }
					
					@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                        super.onReceivedError(view, webResourceRequest, webResourceError);
                        if (webResourceRequest.isForMainFrame()) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
//                            Toast.makeText(DrugClassifyActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                        super.onReceivedError(view, errorCode, description, failingUrl);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            return;
                        }
//                        view.loadUrl("about:blank");// 避免出现默认的错误界面
//                        Toast.makeText(DrugClassifyActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                        super.onReceivedHttpError(view, request, errorResponse);
                        // 这个方法在 android 6.0才出现
                        int statusCode = errorResponse.getStatusCode();
                        if (404 == statusCode || 500 == statusCode) {
//                            view.loadUrl("about:blank");// 避免出现默认的错误界面
                        }
                    }

                 
                });

            }
        }, 100);

    }

    @OnClick({R2.id.iv_back, R2.id.ll_search})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();

        } else if (i == R.id.ll_search) {
            Intent intent = new Intent();
            intent.setClass(DrugClassifyActivity.this, SearchActivity.class);
            startActivity(intent);

        }
    }

    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (classifyWeb != null) {
            //加载null内容
            classifyWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            classifyWeb.clearHistory();
            //销毁VebView
            classifyWeb.destroy();
            //WebView置为null
            classifyWeb = null;
        }
        super.onDestroy();
    }
}
